﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Collections;

namespace Profari_Heldur_Utan_Um_Prof
{
    public partial class StartTask : Form
    {
        //The static variables are used so the variables data won't get lost when user moves between forms
        #region Static variables
        public static int counter = 0;
        public static int length = 0;
        public static int userID;
        public static ArrayList ids = new ArrayList();
        public static int i = 1;
        public static int startTaskPressed = 0;
        #endregion
        
        //Code to connect to the SQL
        #region SQL Connection
        private static SqlConnection con = new SqlConnection("Data Source=orninn.com;Initial Catalog=Notendaprofanir;Persist Security Info=True;User ID=SonjaNew;Password=Léttjógúrt");
        private static DataTable dt = new DataTable();
        private static SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM Project", con);
        private static DataSet ds = new DataSet();
        SqlDataReader r = null;
        #endregion       
        
        #region Variables
        int evalID = StartChooseProject.globalevaluationID;
        int countHelpPressed = 1;
        int bloodPressureID;
        int recordingID;
        #endregion 

        public StartTask()
        {
            this.StartPosition = FormStartPosition.CenterScreen;
            InitializeComponent();

        }

        private void StartTask_Load(object sender, EventArgs e)
        {
            getTaskIDs();
            Change();
            lblHelp.Hide();
            checkIntro();
            formFullScreen();
        }

        //Used when the form is load
        #region Functions
        private void formFullScreen()
        {
            this.WindowState = FormWindowState.Maximized;
            this.FormBorderStyle = FormBorderStyle.None;
        }

        private void Change()
        {
            lblTaskNr.Text = "Task Number: " + i;
           
            getTaskInfo();
            getTaskName();
            getUserID();
            getRecording();
            getBlood();
        }

        private void checkIntro()
        {
            if (StartChooseProject.chkIntroEvaluation)
            {
                string intro = getIntroductionText();
                MessageBox.Show(intro);
            }
        }
        #endregion

        //Code for the buttons in this form
        #region Buttons
        private void btnSkipTask_Click(object sender, EventArgs e)
        {
            DialogResult skipTask = MessageBox.Show("Are you sure you want to skip this task?", "Quit", MessageBoxButtons.YesNo);
            if (skipTask == DialogResult.Yes)
            {
                i++;
                insertIntoSkip();
                counter++;
                if(length <= counter)
                {
                    MessageBox.Show("Skipped");
                    Application.Exit();
                    getUserFeedback();
                }
                else
                    Change();
            }
        }
        private void btnQuit_Click(object sender, EventArgs e)
        {
            DialogResult quitEval = MessageBox.Show("Are you sure you want to exit this test?", "Quit", MessageBoxButtons.YesNo);
            if (quitEval == DialogResult.Yes)
            {
                insertIntoQuit();
                Application.Exit();
            }
        }

        private void btnStartTask_Click(object sender, EventArgs e)
        {
            startTaskPressed++;
            System.Threading.Thread openStartTask = new System.Threading.Thread(new System.Threading.ThreadStart(OpenTask));
            openStartTask.SetApartmentState(System.Threading.ApartmentState.STA);
            openStartTask.Start();
            this.Close();
        }
        private void btnHelp_Click(object sender, EventArgs e)
        {
            if (countHelpPressed % 2 == 1)
            {
                lblHelp.Show();
                countHelpPressed++;
            }
            else if (countHelpPressed % 2 == 0)
            {
                lblHelp.Hide();
                countHelpPressed++;
            }
            
        }

 
        #endregion
        
        //Code for SQL commands
        #region SQL Commands
        private void getTaskIDs()
        {
            try
            {
                con.Open();
                SqlCommand cmd = new SqlCommand("SELECT taskID FROM EvaluationTask WHERE evaluationID = " + evalID + " ORDER BY taskID asc" , con);
                r = cmd.ExecuteReader();
                while (r.Read())
                {
                    ids.Add(Convert.ToInt32(r[0].ToString()));
                    length++;
                }
            }
            catch (SqlException ex)
            {
                Console.WriteLine("Error: {0}", ex.ToString());
            }
            finally
            {
                if (con != null)
                    con.Close();
            }
        }
        private void getTaskInfo()
        {
            try
            {
                con.Open();
                SqlCommand cmd = new SqlCommand("SELECT taskDescription FROM Task WHERE id = " + ids[counter], con);
                r = cmd.ExecuteReader();
                while (r.Read())
                {
                    lblTaskDesc.Text = r.GetString(0);
                    return;
                }
            }
            catch (SqlException ex)
            {
                Console.WriteLine("Error: {0}", ex.ToString());
            }
            finally
            {
                if (con != null)
                    con.Close();
            }
        }
        private void getTaskName()
        {
            try
            {
                con.Open();
                SqlCommand cmd = new SqlCommand("SELECT name FROM Task WHERE id = " + ids[counter], con);
                r = cmd.ExecuteReader();
                while (r.Read())
                {
                    lblTaskName.Text = r.GetString(0);
                    return;
                }
            }
            catch (SqlException ex)
            {
                Console.WriteLine("Error: {0}", ex.ToString());
            }
            finally
            {
                if (con != null)
                    con.Close();
            }
        }
        private void getUserFeedback()
        {
            try
            {
                con.Open();
                SqlCommand cmd = new SqlCommand("SELECT UFQ.isEssay, UFQ.isQuestion, UFQ.isCheckbox FROM UserFeedbackQuestion UFQ INNER JOIN UserFeedback UF ON UFQ.UserFeedbackID = UF.id INNER JOIN GroupEvaluations GE ON UFQ.UserFeedbackID = UF.id AND GE.groupsID = " + StartChooseProject.globalgroupsID + " AND GE.evaluationID = " + StartChooseProject.globalevaluationID, con);
                r = cmd.ExecuteReader();
                while (r.Read())
                {
                    /*
                    if (r.GetBoolean(0) == true)
                    {
                        System.Threading.Thread OpenEssay = new System.Threading.Thread(new System.Threading.ThreadStart(openEssay));
                        OpenEssay.SetApartmentState(System.Threading.ApartmentState.STA);
                        OpenEssay.Start();
                        this.Close();
                    }
                    else if (r.GetBoolean(1) == true)
                    {
                        System.Threading.Thread OpenSurvey = new System.Threading.Thread(new System.Threading.ThreadStart(openSurvey));
                        OpenSurvey.SetApartmentState(System.Threading.ApartmentState.STA);
                        OpenSurvey.Start();
                        this.Close();
                    }
                    else if (r.GetBoolean(2) == true)
                    {
                        System.Threading.Thread OpenCheckboxes = new System.Threading.Thread(new System.Threading.ThreadStart(openCheckboxes));
                        OpenCheckboxes.SetApartmentState(System.Threading.ApartmentState.STA);
                        OpenCheckboxes.Start();
                        this.Close();
                    }
                    else
                    {
                     * */
                        MessageBox.Show("Thank you for participating in this evaluation");
                        Application.Exit();
                    
                }
            }

            catch (SqlException ex)
            {
                Console.WriteLine("Error: {0}", ex.ToString());
            }
            finally
            {
                if (con != null)
                    con.Close();
            }
        }
        private void getUserID()
        {
            try
            {
                con.Open();
                SqlCommand cmd = new SqlCommand("SELECT TOP 1 id FROM UserInfo ORDER BY id desc", con);
                r = cmd.ExecuteReader();
                while (r.Read())
                {
                    userID = r.GetInt32(0);
                }
            }
            catch (SqlException ex)
            {
                Console.WriteLine("Error: {0}", ex.ToString());
            }
            finally
            {
                if (con != null)
                    con.Close();
            }
        }
        private void getBlood()
        {
            try
            {
                con.Open();
                SqlCommand cmd = new SqlCommand("SELECT TOP 1 id FROM BloodPressure ORDER BY id desc", con);
                r = cmd.ExecuteReader();
                while (r.Read())
                {
                    bloodPressureID = r.GetInt32(0);
                    return;
                }
            }
            catch (SqlException ex)
            {
                Console.WriteLine("Error: {0}", ex.ToString());
            }
            finally
            {
                if (con != null)
                    con.Close();
            }
        }
        private void getRecording()
        {
            try
            {
                con.Open();
                SqlCommand cmd = new SqlCommand("SELECT TOP 1 id FROM Recording ORDER BY id desc", con);
                r = cmd.ExecuteReader();
                while (r.Read())
                {
                    recordingID = r.GetInt32(0);
                }
            }
            catch (SqlException ex)
            {
                Console.WriteLine("Error: {0}", ex.ToString());
            }
            finally
            {
                if (con != null)
                    con.Close();
            }
        }
        private void insertIntoSkip()
        {
            try
            {
                con.Open();
                SqlCommand cmd = new SqlCommand("INSERT INTO TaskUser(taskID, userInfoID, recordingID, bloodPressureID, sortButtons) VALUES('" + ids[counter] + "' ,'" + userID + "' ,'" + recordingID + "' ,'" + bloodPressureID + "'  , 2)", con);
                cmd.ExecuteNonQuery();

            }
            catch (SqlException ex)
            {
                Console.WriteLine("Error: {0}", ex.ToString());

            }
            finally
            {
                if (con != null)
                {
                    con.Close();
                }
            }
        }
        private void insertIntoQuit()
        {
            try
            {
                con.Open();
                SqlCommand cmd = new SqlCommand("INSERT INTO TaskUser(taskID, userInfoID, recordingID, bloodPressureID, sortButtons) VALUES(" + StartTask.ids[StartTask.counter] + " ," + userID + " ," + recordingID + " ," + bloodPressureID + "  , 0)", con);
                cmd.ExecuteNonQuery();

            }
            catch (SqlException ex)
            {
                Console.WriteLine("Error: {0}", ex.ToString());

            }
            finally
            {
                if (con != null)
                {
                    con.Close();
                }
            }
        }
        private int getIntroductionID()
        {
            try
            {
                con.Open();
                SqlCommand cmd = new SqlCommand("SELECT introBeforeEvaluationID FROM EvaluationTask WHERE evaluationID="+evalID + "AND taskID="+ids[i-1], con);
                r = cmd.ExecuteReader();
                while (r.Read())
                {
                    return r.GetInt32(0);
                }
            }
            catch (SqlException ex)
            {
                Console.WriteLine("Error: {0}", ex.ToString());
            }
            finally
            {
                if (con != null)
                    con.Close();
            }
            return 0;
        }
        private string getIntroductionText()
        {
            int id = getIntroductionID();
            try
            {
                con.Open();
                SqlCommand cmd = new SqlCommand("SELECT introDescription FROM IntroBeforeEvaluation WHERE id="+id, con);
                r = cmd.ExecuteReader();
                while (r.Read())
                {
                    return r.GetString(0);
                }
            }
            catch (SqlException ex)
            {
                Console.WriteLine("Error: {0}", ex.ToString());
            }
            finally
            {
                if (con != null)
                    con.Close();
            }
            return null;
        }
        #endregion

        //The Open forms functions makes it able to move between forms and close the first form when the second one is opened
        #region OpenForms
        public static void OpenTask()
        {
            //Create an instance of your new form. No need to call show method.
            Application.Run(new TakeTask());
        }
        private void openEssay()
        {
            Application.Run(new Essay());
        }
        private void openSurvey()
        {
            Application.Run(new Survey());
        }
        #endregion


    }
}
